package com.zhanghe.util;

import java.io.File;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

public class AnnotationUtil {

	public static void scanPackage(String basePacakgeName,Callback callback){
		String path = basePacakgeName.replaceAll("\\.", "/");
		System.out.println("path:"+path);
		//获取这个路径的URL对象
		URL url = Thread.currentThread().getContextClassLoader().getResource(path);
		System.out.println("url:"+url.getPath());
		try{
			if(url!=null&&url.toString().startsWith("file")){
				//url是文件
				//获取文件路径
				String filePath = URLDecoder.decode(url.getFile(),"UTF-8");
				File dir = new File(filePath);
				List<File> list = new ArrayList<File>(); 
				fetchFileList(dir,list);
				for(File file:list){
					String fileName = file.getAbsolutePath();
					if(fileName.endsWith(".class")){
						//是class文件
						String nosuffixFileName = fileName.substring(8 + fileName.lastIndexOf("classes"), fileName.indexOf(".class"));
                        String filePackage = nosuffixFileName.replaceAll("\\\\", ".");
                        Class<?> clazz = Class.forName(filePackage);
                        callback.callback(file, clazz);
					}else{
						callback.callback(file, null);
					}
				}
			}
		}catch (Exception e){
			e.printStackTrace();
		}
	}
    private static void fetchFileList(File dir, List<File> fileList) {
        if (dir.isDirectory()) {
            for (File f : dir.listFiles()) {
                fetchFileList(f, fileList);
            }
        } else {
            fileList.add(dir);
        }
    }
	public interface Callback{
		void callback(File file, Class<?> clazz) throws InstantiationException, IllegalAccessException;
	}
}
